package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ArticleHomeDTO;
import com.heima.model.wemedia.pojos.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Value("${file.oss.web-site}")
    String webSite;
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private AuthorMapper authorMapper;
    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    GeneratePageService generatePageService;

    @Value("${file.minio.readPath}")
    String readPath;

    /**
     * 文章发布
     *
     * @param newsId
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public void publishArticle(Integer newsId) {
        //检查参数
        if (newsId == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        ResponseResult<WmNews> wmNewsResult = wemediaFeign.selectOne(newsId);
        if (!wmNewsResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        if (wmNewsResult.getData() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        WmNews wmNews = wmNewsResult.getData();
        if (wmNews.getStatus() != WmNews.Status.ADMIN_SUCCESS.getCode() && wmNews.getStatus() != WmNews.Status.SUCCESS.getCode()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章不是待发布状态不能发布");
        }
        //封装article
        ApArticle apArticle = setApArticle(wmNews);
        //article保存还是修改信息
        saveOrUpdateAparticle(apArticle);
        //保存关联配置信息
        saveConfigAndContent(wmNews, apArticle);
        //TODO页面静态化
        generatePageService.generateArticlePage(wmNews.getContent(),apArticle);
        //更新wmnewS状态 设置articleId
        wmNews.setArticleId(apArticle.getId());

        wmNews.setStatus(WmNews.Status.PUBLISHED.getCode());
        ResponseResult responseResult = wemediaFeign.updateWmnews(wmNews);
        if (!responseResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
    }


    /**
     * 保存关联配置信息
     *
     * @param wmNews
     * @param apArticle
     */
    private void saveConfigAndContent(WmNews wmNews, ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsDelete(false);
        apArticleConfigMapper.insert(apArticleConfig);
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        apArticleContentMapper.insert(apArticleContent);


    }

    /**
     * 判断之前文章是否关联Article
     *
     * @param apArticle
     */
    private void saveOrUpdateAparticle(ApArticle apArticle) {
        if (apArticle.getId() == null) {
            //无关联保存
            apArticle.setCollection(0);
            apArticle.setComment(0);
            apArticle.setLikes(0);
            apArticle.setViews(0);
            apArticle.setCreatedTime(new Date());
            save(apArticle);
        } else {
            //有关联 ，修改
            //删除之前的配置信息
            ApArticle article = getById(apArticle.getId());
            if (article == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            updateById(apArticle);
            apArticleConfigMapper.delete(Wrappers.<ApArticleConfig>lambdaQuery()
                    .eq(ApArticleConfig::getArticleId, apArticle.getId()));
            apArticleContentMapper.delete(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId, apArticle.getId()));
        }
    }

    /**
     * 封装articlle对象
     *
     * @param wmNews
     * @return
     */
    private ApArticle setApArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(wmNews, apArticle);
        apArticle.setId(wmNews.getArticleId());
        apArticle.setFlag((byte) 0);
        apArticle.setLayout(wmNews.getType());
        ResponseResult<AdChannel> adChannerResult = adminFeign.selectOne(wmNews.getChannelId());
        if (!adChannerResult.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        AdChannel adChannel = adChannerResult.getData();
        if (adChannel == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "未查询到相关信息");
        }
        apArticle.setChannelName(adChannel.getName());
        ApAuthor apAuthor = authorMapper.selectOne(Wrappers.<ApAuthor>lambdaQuery().eq(ApAuthor::getWmUserId, wmNews.getUserId()));
        if (apAuthor == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "作者信息不存在");
        }

        apArticle.setAuthorId(Long.valueOf(apAuthor.getId()));
        apArticle.setAuthorName(apAuthor.getName());
        return apArticle;

    }

    /**
     * app端加载
     *
     * @param dto
     * @param type
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDTO dto, Short type) {
        //  校验参数
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        //频道
        if (StringUtils.isBlank(dto.getTag())) {
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        //时间
        if (dto.getMaxBehotTime() == null) {
            dto.setMaxBehotTime(new Date());
        }
        if (dto.getMinBehotTime() == null) {
            dto.setMinBehotTime(new Date());
        }
        //类型判断
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(type) && !ArticleConstants.LOADTYPE_LOAD_NEW.equals(type)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        //执行查询
        List<ApArticle> apArticles = apArticleMapper.loadmoreAndNew(dto, type);
        for (ApArticle apArticle : apArticles) {
            String images = apArticle.getImages();
            if (StringUtils.isNotBlank(images)){
                images=Arrays.stream(images.split(",")).map(url->webSite+url).collect(Collectors.joining(","));
                apArticle.setImages(images);
            } apArticle.setStaticUrl(readPath+apArticle.getStaticUrl());
        }
        //返回结果
        ResponseResult responseResult = ResponseResult.okResult(apArticles);
        return responseResult;
    }
}